package callLinuxCommand.callLinuxCommand;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class CommandUtils {
	// 字符编码默认是utf-8
	private static String DEFAULTCHART = "UTF-8";
	
	public static Connection conn = null;
	public static Session session = null;

	public static void initSession(String hostname, String username, String password) {
		boolean isAuthenticated = false;

		try {
			if (conn == null) {
				conn = new Connection(hostname);
				conn.connect();
			}
			isAuthenticated = conn.authenticateWithPassword(username, password);
			if (session == null) {
				session = conn.openSession();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (isAuthenticated == false) {
			System.out.println("登录失败!");
		}
		System.out.println("登录" + hostname + "成功!用户:" + username + " 密码" + password);

	}

	public static void close() {
		if (conn != null) {
			System.out.println("关闭连接!");
			conn.close();
			conn = null;
		}
		if (session != null) {
			System.out.println("关闭session!");
			session.close();
			session = null;
		}
	}

	/**
	 * 解析脚本执行返回的结果集
	 * 
	 * @author Ickes
	 * @param in
	 *            输入流对象
	 * @param charset
	 *            编码
	 * @since V0.1
	 * @return 以纯文本的格式返回
	 */
	private static String processStdout(InputStream in, String charset) {
		InputStream stdout = new StreamGobbler(in);
		StringBuffer buffer = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
			String line = null;
			while ((line = br.readLine()) != null) {
				buffer.append(line + "\n");
			}
			br.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}

	public static String execute(String cmd) {
		String result = "";
		try {
			session.execCommand(cmd);// 执行命令
			result = processStdout(session.getStdout(), DEFAULTCHART);
			// 如果为得到标准输出为空，说明脚本执行出错了
			if (result == null || result == "") {
				result = processStdout(session.getStderr(), DEFAULTCHART);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public static void main(String[] args) {
		CommandUtils.initSession("211.88.12.114", "root", "root20170522");
		System.out.println(CommandUtils.execute("uname -a && date && uptime && mkdir /tmp/testtest/t1"));
		CommandUtils.close();
		CommandUtils.initSession("211.88.12.114", "root", "root20170522");
		System.out.println(CommandUtils.execute("ls /tmp/testtest"));
		CommandUtils.close();
		
		
	}

}
